//
//  CMVideoSplashController.swift
//  Runner
//
//  Created by admin on 2025/9/27.
//

import UIKit
import AVFoundation

class CMVideoSplashController: UIViewController {
    
    // MARK: - VSC Properties
    private var vscPlayerLayer: AVPlayerLayer!
    private var vscPlayer: AVPlayer!
    private var vscCountdownButton: UIButton!
    private var vscEnterButton: UIButton!
    private var vscCountdownTimer: Timer?
    private var vscCountdownSeconds: Int = 6
    private var vscMainTimer: Timer?
    private var vscPlaceholderImageView: UIImageView!
    
    // MARK: - VSC First Launch Detection
    private static let vscFirstLaunchKey = "VSCHasLaunchedBefore"
    
    // MARK: - VSC Callback Properties
    var vscCompletionHandler: (() -> Void)?
    var vscFirstFrameLoadedHandler: (() -> Void)?
    
    // MARK: - VSC Static Methods
    static func vscShouldShowSplash() -> Bool {
        return !UserDefaults.standard.bool(forKey: vscFirstLaunchKey)
    }
    
    static func vscMarkAsLaunched() {
        UserDefaults.standard.set(true, forKey: vscFirstLaunchKey)
        UserDefaults.standard.synchronize()
        print("🎯 应用已标记为非首次启动")
    }
    
    // MARK: - VSC Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 检查是否为首次启动
        if !CMVideoSplashController.vscShouldShowSplash() {
            print("⚡ 非首次启动，直接跳转到主应用")
            DispatchQueue.main.async { [weak self] in
                self?.vscCompletionHandler?()
            }
            return
        }
        
        print("🎬 首次启动，显示视频启动页")
        vscSetupPlaceholderImage()
        vscSetupVideoPlayer()
        vscSetupUI()
        vscStartCountdown()
        vscStartMainTimer()
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(vscAppsFlyerSuccess(_:)),
            name: NSNotification.Name("VSCAppsFlyerResult"),
            object: nil
        )
    }
    
    @objc private func vscAppsFlyerSuccess(_ notification: Notification) {
        vscShowEnterButton()
   }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if CMVideoSplashController.vscShouldShowSplash() {
            vscPlayerLayer?.frame = view.bounds
            vscPlaceholderImageView?.frame = view.bounds
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        vscCleanupTimers()
        vscPlayer?.pause()
    }
    
    // MARK: - VSC Setup Methods
    private func vscSetupPlaceholderImage() {
        vscPlaceholderImageView = UIImageView(image: UIImage(named: "laun"))
        vscPlaceholderImageView.contentMode = .scaleAspectFill
        vscPlaceholderImageView.clipsToBounds = true
        vscPlaceholderImageView.frame = view.bounds
        view.addSubview(vscPlaceholderImageView)
        
        print("🖼️ 启动占位图片已设置")
    }
    
    private func vscSetupVideoPlayer() {
        guard let vscVideoPath = Bundle.main.path(forResource: "iuvideo", ofType: "MOV") else {
            print("❌ 视频文件未找到")
            return
        }
        
        let vscVideoURL = URL(fileURLWithPath: vscVideoPath)
        vscPlayer = AVPlayer(url: vscVideoURL)
        vscPlayerLayer = AVPlayerLayer(player: vscPlayer)
        
        vscPlayerLayer.videoGravity = .resizeAspectFill
        vscPlayerLayer.frame = view.bounds
        view.layer.addSublayer(vscPlayerLayer)
        
        // 循环播放
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(vscVideoDidEnd),
            name: .AVPlayerItemDidPlayToEndTime,
            object: vscPlayer.currentItem
        )
        
        // 监听视频第一帧加载完成
        vscPlayer.currentItem?.addObserver(self, forKeyPath: "status", options: [.new, .initial], context: nil)
        
        vscPlayer.play()
    }
    
    private func vscSetupUI() {
        vscSetupCountdownButton()
        vscSetupEnterButton()
    }
    
    private func vscSetupCountdownButton() {
        vscCountdownButton = UIButton(type: .custom)
        vscCountdownButton.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        vscCountdownButton.setTitleColor(.white, for: .normal)
        vscCountdownButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        vscCountdownButton.layer.cornerRadius = 20
        vscCountdownButton.layer.masksToBounds = true
        vscCountdownButton.addTarget(self, action: #selector(vscEnterButtonSkipTapped), for: .touchUpInside)
        
        view.addSubview(vscCountdownButton)
        
        // 设置约束
        vscCountdownButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            vscCountdownButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            vscCountdownButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            vscCountdownButton.widthAnchor.constraint(equalToConstant: 80),
            vscCountdownButton.heightAnchor.constraint(equalToConstant: 40)
        ])
        
        vscUpdateCountdownButton()
    }
    
    private func vscSetupEnterButton() {
        vscEnterButton = UIButton(type: .custom)
        vscEnterButton.backgroundColor = UIColor.systemBlue
        vscEnterButton.setTitle("Enter", for: .normal)
        vscEnterButton.setTitleColor(.white, for: .normal)
        vscEnterButton.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        vscEnterButton.layer.cornerRadius = 25
        vscEnterButton.layer.masksToBounds = true
        vscEnterButton.addTarget(self, action: #selector(vscEnterButtonTapped), for: .touchUpInside)
        
        // 添加阴影效果
        vscEnterButton.layer.shadowColor = UIColor.black.cgColor
        vscEnterButton.layer.shadowOffset = CGSize(width: 0, height: 2)
        vscEnterButton.layer.shadowOpacity = 0.3
        vscEnterButton.layer.shadowRadius = 4
        vscEnterButton.layer.masksToBounds = false
        
        // 初始时隐藏按钮
        vscEnterButton.alpha = 0
        vscEnterButton.isHidden = true
        
        view.addSubview(vscEnterButton)
        
        // 设置约束
        vscEnterButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            vscEnterButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40),
            vscEnterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            vscEnterButton.widthAnchor.constraint(equalToConstant: 200),
            vscEnterButton.heightAnchor.constraint(equalToConstant: 50)
        ])
    }
    
    // MARK: - VSC Timer Methods
    private func vscStartCountdown() {
        vscCountdownTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
            self?.vscUpdateCountdown()
        }
    }
    
    private func vscStartMainTimer() {
        vscMainTimer = Timer.scheduledTimer(withTimeInterval: 8.0, repeats: false) { [weak self] _ in
            self?.vscShowSkipButton()
        }
    }
    
    private func vscUpdateCountdown() {
        if vscCountdownSeconds > 0 {
            vscCountdownSeconds -= 1
            vscUpdateCountdownButton()
        } else {
            vscCountdownTimer?.invalidate()
            vscCountdownTimer = nil
        }
    }
    
    private func vscUpdateCountdownButton() {
        if vscCountdownSeconds > 0 {
            vscCountdownButton.setTitle("\(vscCountdownSeconds)s", for: .normal)
            vscCountdownButton.isEnabled = false
            vscCountdownButton.alpha = 0.8
        }
    }
    
    private func vscShowSkipButton() {
        UIView.animate(withDuration: 0.3) { [weak self] in
            self?.vscCountdownButton.setTitle("Skip", for: .normal)
            self?.vscCountdownButton.isEnabled = true
            self?.vscCountdownButton.alpha = 1.0
            self?.vscCountdownButton.backgroundColor = UIColor.systemRed.withAlphaComponent(0.8)
        }
        
        // 7秒倒计时结束后显示进入按钮
        vscShowEnterButton()
    }
    
    // MARK: - VSC Show Enter Button Method
    private func vscShowEnterButton() {
        vscEnterButton.isHidden = false
        
        // 添加淡入动画效果
        UIView.animate(withDuration: 0.5, delay: 0.2, options: .curveEaseOut) { [weak self] in
            self?.vscEnterButton.alpha = 1.0
        } completion: { [weak self] _ in
            // 动画完成后添加呼吸动画效果
            self?.vscAddButtonAnimation()
        }
    }
    
    
    
    private func vscCleanupTimers() {
        vscCountdownTimer?.invalidate()
        vscCountdownTimer = nil
        vscMainTimer?.invalidate()
        vscMainTimer = nil
    }
    
    // MARK: - VSC Animation Methods
    private func vscAddButtonAnimation() {
        // 添加呼吸动画效果
        let vscPulseAnimation = CABasicAnimation(keyPath: "transform.scale")
        vscPulseAnimation.duration = 1.5
        vscPulseAnimation.fromValue = 1.0
        vscPulseAnimation.toValue = 1.05
        vscPulseAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        vscPulseAnimation.autoreverses = true
        vscPulseAnimation.repeatCount = .infinity
        
        vscEnterButton.layer.add(vscPulseAnimation, forKey: "vscPulseAnimation")
    }
    

    
    @objc private func vscEnterButtonTapped() {
        // 添加点击动画
        UIView.animate(withDuration: 0.1, animations: { [weak self] in
            self?.vscEnterButton.transform = CGAffineTransform(scaleX: 0.95, y: 0.95)
        }) { [weak self] _ in
            UIView.animate(withDuration: 0.1) {
                self?.vscEnterButton.transform = .identity
            }
            self?.vscNavigateToMainApp()
        }
    }
    
    @objc func vscEnterButtonSkipTapped() {
        self.vscNavigateToMainApp()
    }
    
    @objc private func vscVideoDidEnd() {
        // 视频播放结束后重新开始
        vscPlayer.seek(to: .zero)
        vscPlayer.play()
    }
    
    // MARK: - VSC KVO Observer
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "status" {
            if let playerItem = object as? AVPlayerItem {
                switch playerItem.status {
                case .readyToPlay:
                    print("🎬 视频第一帧加载完成")
                    DispatchQueue.main.async { [weak self] in
                        self?.vscHidePlaceholderImage()
                        self?.vscFirstFrameLoadedHandler?()
                    }
                case .failed:
                    print("❌ 视频加载失败: \(playerItem.error?.localizedDescription ?? "未知错误")")
                case .unknown:
                    print("⏳ 视频状态未知")
                @unknown default:
                    break
                }
            }
        }
    }
    
    // MARK: - VSC Placeholder Image Methods
    private func vscHidePlaceholderImage() {
        UIView.animate(withDuration: 0.3, animations: { [weak self] in
            self?.vscPlaceholderImageView.alpha = 0
        }) { [weak self] _ in
            self?.vscPlaceholderImageView.isHidden = true
            print("🎬 占位图片已隐藏，视频开始播放")
        }
    }
    
    // MARK: - VSC Navigation Methods
    private func vscNavigateToMainApp() {
        vscCleanupTimers()
        vscPlayer?.pause()
        
        // 标记为已启动过
        CMVideoSplashController.vscMarkAsLaunched()
        
        self.vscCompletionHandler?()
    }
    
    // MARK: - VSC Deinit
    deinit {
        vscCleanupTimers()
        vscPlayer?.currentItem?.removeObserver(self, forKeyPath: "status")
        NotificationCenter.default.removeObserver(self)
        print("🗑️ CMVideoSplashController 已释放")
    }
}
